package com.kkb.controller.login;

import com.kkb.bean.User;
import com.kkb.service.login.LoginService;
import com.kkb.vo.BaseResp;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@RestController
@RequestMapping("/user")
public class MyLoginController {

    @Autowired
    private LoginService loginService;

    @PostMapping("/findByName")
    public BaseResp<Map<String,Object>> findByName(String username){
        //1.判断username是不是为空
        if(username == null){
            return new BaseResp<>("1000",true,"用户名为空");
        }
        //2.根据username判断是否不存在
        List<User> list = loginService.findByName(username);
        if (list.size() == 0){
            return new BaseResp<>("800",true,"用户名不存在");
        }
        //3、返回用户名正确
        Map<String, Object> map = new HashMap<>();
        map.put("list",list);
        return new BaseResp<>(map);
    }



    @PostMapping("/denglu")
    public BaseResp<Map<String,Object>> denglu(String username,String password, HttpServletRequest request){
        HttpSession session = request.getSession();
        if (username == null || password == null){
            return new BaseResp<>("800",true,"用户名或密码为空");
        }
//        session.setAttribute("user",user);
        //判断用户名或密码是否正确
        //如果正确，登录成功，如果错误，输出用户名或者密码不正确
        List<User> list = loginService.denglu(username, password);
        User user;
        if (list.size()==0){
            //不成功
            return new BaseResp<>("800",true,"用户名或密码错误");
        }else {
            //登录成功
            user = list.get(0);
            session.setAttribute("user",user);
            session.setAttribute("id",user.getUserId());
            Map<String, Object> map = new HashMap<>();
            map.put("list",list);
            return new BaseResp<>(map);
        }
    }

    @PostMapping("/zhuce")
    public BaseResp<Map<String,Object>> zhuce(String username,String password,String password2, String phonenumber){
        //注册
        //1.用户名和密码不能为空
        if (username == null || password == null){
            return new BaseResp<>("800",true,"用户名或密码为空");
        }
        //2.判断用户名是否存在
        List<User> list = loginService.findByName(username);
        if (list.size() == 1){
            return new BaseResp<>("900",true,"用户名已存在");
        }
        //3.判断两次密码是否一致
        if(!password2.equals(password)){
            return new BaseResp<>("500",true,"两次密码不一致！");
        }
        //4.判断手机号合不合法
        if (phonenumber.length() != 11 ){
            return new BaseResp<>("700",true,"必须输入11位的数字");
        }
        int zhuce = loginService.zhuce(username, password, phonenumber);
        if(zhuce == 0){
            return new BaseResp<>("600",true,"注册失败");
        }else {
            return new BaseResp<>();
        }
    }

}
